package com.njbdqn.myshops.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
public class ShopCartCtrl {
    @Autowired
    private StringRedisTemplate srt;
    private final static String SUCCESS = "{\"status\":\"200\"}";

    @RequestMapping("/savecart")
    public String saveGoodsToShopCart(int cust_id,int good_id,int buy_num){
        // 检查该用户是否有购物车
        System.out.println(srt.opsForHash().size("car_" + cust_id+""));
        //用户还没有购物车
        if(srt.opsForHash().size("car_"+cust_id)==0){
            srt.opsForHash().put("car_"+cust_id+"",good_id+"",buy_num+"");
        }else {
            //用户已经有购物车，那么判断是否有该商品
            Object o = srt.opsForHash().get("car_" + cust_id+"", good_id + "");
            if (null==o){
                srt.opsForHash().put("car_"+cust_id+"",good_id+"",buy_num+"");
            }else{
                int orignNum = Integer.parseInt(o.toString());
                srt.opsForHash().put("car_"+cust_id+"",good_id+"",orignNum+buy_num+"");
            }
        }
        return SUCCESS;
    }
}
